<template>
    <div class="purchase-return-container">
        <!-- 搜索栏 -->
        <div class="search-bar" style="margin-bottom: 15px;margin-left: 30px;">
            <el-input v-model="searchParams.returnNo" style="width: 240px; padding-right: 15px;" placeholder="请输入退货单号" />
            <el-input v-model="searchParams.inboundNo" style="width: 240px;" placeholder="请输入入库单号" />
<!--            <el-date-picker v-model="searchParams.startDate" type="date" placeholder="起始日期" value-format="YYYY-MM-DD" format="YYYY-MM-DD" style="margin-right: 10px;margin-left: 10px; width: 150px;" />-->
<!--            <el-date-picker v-model="searchParams.endDate" type="date" placeholder="结束日期" value-format="YYYY-MM-DD" format="YYYY-MM-DD" style="width: 150px;" />-->
            <el-icon @click="getPurchaseReturnList()" style="margin-left: 20px; height: 25px; width: 25px;">
                <Search />
            </el-icon>
            <el-icon style="margin-left: 20px;" @click="resetSearchParams()">
                <Refresh />
            </el-icon>
            <el-button type="success" plain style="margin-left: 30px;" @click="showAddDialog()">创建采购退货单</el-button>
        </div>

        <!-- 采购退货单表格 -->
        <el-table :data="purchaseReturnList" style="width: 100%" stripe border="true">
            <el-table-column label="序号" width="80px" #default="scope" align="center">
                {{ scope.$index + 1 }}
            </el-table-column>
            <el-table-column prop="id" label="退货单ID" width="180" align="center" />
            <el-table-column prop="returnNo" label="退货单号" width="180" align="center" />
            <el-table-column prop="inboundNo" label="入库单号" width="180" align="center" />
            <el-table-column prop="warehouseName" label="仓库名称" width="180" align="center" />
            <el-table-column prop="returnDate" label="退货日期" width="180" align="center" />
            <el-table-column prop="status" label="退货状态" width="120" #default="scope" align="center">
                <span v-if="scope.row.status == 0" style="color: gray;">草稿</span>
                <span v-if="scope.row.status == 1" style="color: green;">已退货</span>
                <span v-if="scope.row.status == 2" style="color: red;">已取消</span>
            </el-table-column>
            <el-table-column label="操作" width="250px" fixed="right" align="center" #default="scope">
                <el-button type="primary" plain @click="viewPurchaseReturnDetails(scope.row.id)">详情</el-button>
                <el-button type="warning" plain @click="showEditDialog(scope.row)">修改</el-button>
                <el-button type="danger" plain @click="handleDeletePurchaseReturn(scope.row.id)">删除</el-button>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div style="position: absolute;bottom: 20px;left: 0;right: 0;height: 25px;width: 300px;margin: 0 auto; ">
            <el-pagination v-model:current-page="pagination.pageNum" v-model:page-size="pagination.pageSize"
                :page-sizes="[3, 5, 10]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 创建/编辑采购退货单对话框 -->
        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑采购退货单' : '创建采购退货单'" width="900px"
            :before-close="handleDialogClose" :close-on-click-modal="false">
            <el-form :model="purchaseReturn" label-width="120px" style="padding: 15px 0;" :rules="formRules" ref="returnForm">
                <el-form-item label="退货单号" prop="returnNo" v-if="isEdit">
                    <el-input v-model="purchaseReturn.returnNo" disabled placeholder="系统自动生成" />
                </el-form-item>
                <el-form-item label="入库单号" prop="inboundId">
                    <el-select v-model="purchaseReturn.inboundId" placeholder="请选择入库单" clearable @change="handleInboundChange">
                        <el-option v-for="inbound in purchaseInbounds" :key="inbound.id" :label="inbound.inboundNo" :value="inbound.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="仓库名称" prop="warehouseId">
                    <el-input v-model="purchaseReturn.warehouseName" placeholder="将从选择的入库单自动获取" disabled />
                    <!-- 隐藏的仓库ID字段用于表单提交 -->
                    <input type="hidden" v-model="purchaseReturn.warehouseId" />
                </el-form-item>
                <el-form-item label="退货日期" prop="returnDate">
                    <el-date-picker v-model="purchaseReturn.returnDate" type="date" placeholder="请选择退货日期" value-format="YYYY-MM-DD" format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item label="退货状态" prop="status" v-if="isEdit">
                    <el-select v-model="purchaseReturn.status" placeholder="请选择退货状态">
                        <el-option label="已退货" :value="1" />
                        <el-option label="已取消" :value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="purchaseReturn.remark" type="textarea" placeholder="请输入备注信息" />
                </el-form-item>
            </el-form>

            <!-- 新增：退货商品明细表格 -->
            <div style="margin: 10px 0 0 0;">
                <h4>退货商品明细</h4>
                <el-table :data="purchaseReturn.items || []" style="width: 100%; margin-bottom: 10px;">
                    <el-table-column label="序号" width="60" #default="scope" align="center">
                        {{ scope.$index + 1 }}
                    </el-table-column>
                    <el-table-column label="产品" width="200" #default="scope" align="center">
                        <span>{{ scope.row.productName || '未知产品' }}</span>
                    </el-table-column>
                    <el-table-column label="产品编码" width="150" #default="scope" align="center">
                        <span>{{ scope.row.productCode || '-' }}</span>
                    </el-table-column>
                    <el-table-column label="数量" width="120" #default="scope" align="center">
                        <span>{{ scope.row.quantity || 0 }}</span>
                    </el-table-column>
                    <el-table-column label="单价" width="120" #default="scope" align="center">
                        <span>{{ scope.row.unitPrice || 0 }}</span>
                    </el-table-column>
                    <el-table-column label="金额" width="120" #default="scope" align="center">
                        <span>{{ scope.row.amount || 0 }}</span>
                    </el-table-column>
                </el-table>
            </div>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleDialogClose" size="default">取消</el-button>
                    <el-button type="primary" @click="submitForm" size="default">确认{{ isEdit ? '修改' : '创建' }}</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 采购退货单详情对话框 -->
        <el-dialog v-model="detailDialogVisible" title="采购退货单详情" width="900px" :before-close="handleDetailDialogClose" :close-on-click-modal="false">
            <div v-if="currentPurchaseReturn" class="purchase-detail">
                <div class="detail-header">
                    <p><span class="label">退货单号：</span>{{ currentPurchaseReturn.returnNo }}</p>
                    <p><span class="label">入库单号：</span>{{ currentPurchaseReturn.inboundNo }}</p>
                    <p><span class="label">仓库名称：</span>{{ currentPurchaseReturn.warehouseName }}</p>
                    <p><span class="label">退货日期：</span>{{ currentPurchaseReturn.returnDate }}</p>
                    <p><span class="label">退货状态：</span>
                        <span v-if="currentPurchaseReturn.status == 0" style="color: gray;">草稿</span>
                        <span v-if="currentPurchaseReturn.status == 1" style="color: green;">已退货</span>
                        <span v-if="currentPurchaseReturn.status == 2" style="color: red;">已取消</span>
                    </p>
                    <p><span class="label">备注：</span>{{ currentPurchaseReturn.remark }}</p>
                </div>

                <div class="detail-items">
                    <h3>采购退货单明细</h3>
                    <el-table :data="currentPurchaseReturn.items" style="width: 100%" stripe>
                        <el-table-column label="序号" width="80px" #default="scope" align="center">
                            {{ scope.$index + 1 }}
                        </el-table-column>
                        <el-table-column prop="productName" label="产品名称" width="180" align="center" />
                        <el-table-column prop="productCode" label="产品编码" width="180" align="center" />
                        <el-table-column prop="quantity" label="数量" width="120" align="center" />
                        <el-table-column prop="unitPrice" label="单价" width="120" align="center" />
                        <el-table-column prop="amount" label="金额" width="120" align="center" />
                    </el-table>
                </div>
            </div>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleDetailDialogClose" size="default">关闭</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, getCurrentInstance, onMounted } from 'vue';
import { Search, Refresh } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
// 导入所有需要的API方法
import { createPurchaseReturn, getPurchaseReturnPage, getPurchaseReturnWithDetails, updatePurchaseReturn, deletePurchaseReturn } from '@/api/purchase/purchase_return';
import { getPurchaseInboundPage, getWarehouse, getPurchaseInboundWithDetails } from '@/api/purchase/purchase_inbound';
// 不再需要产品列表API，因为商品明细现在是只读的
// import { getProductList } from '@/api/warehouse/warehouse';

// 获取组件实例用于表单验证
const { proxy } = getCurrentInstance();

// 采购退货单列表数据
const purchaseReturnList = ref([]);

// 采购入库单列表数据（用于选择）
const purchaseInbounds = ref([]);

// 仓库列表数据（用于选择）
const warehouses = ref([]);

// 不再需要产品列表数据，因为商品明细现在是只读的
// const productList = ref([]);

// 搜索参数
const searchParams = ref({
    returnNo: '',
    inboundNo: '',
    startDate: '',
    endDate: ''
});

// 分页参数
const pagination = ref({
    pageNum: 1,
    pageSize: 10,
    total: 0
});

// 对话框状态
const dialogVisible = ref(false);
const detailDialogVisible = ref(false);
const isEdit = ref(false);

// 当前操作的采购退货单
const purchaseReturn = ref({});
const currentPurchaseReturn = ref(null);

// 统一解包工具：兼容拦截器返回 data 或原始对象
function unwrap(res) {
  return (res && res.data !== undefined) ? res.data : res;
}

// 表单验证规则
const formRules = ref({
    inboundId: [
        { required: true, message: '请选择入库单', trigger: 'blur' }
    ],
    returnDate: [
        { required: true, message: '请选择退货日期', trigger: 'change' }
    ]
});

// 获取采购退货单列表
function getPurchaseReturnList() {
    // 构建分页参数
    const pageParams = {
        pageNum: pagination.value.pageNum,
        pageSize: pagination.value.pageSize,
        returnNo: searchParams.value.returnNo,
        inboundNo: searchParams.value.inboundNo,
        startDate: searchParams.value.startDate,
        endDate: searchParams.value.endDate
    };

    getPurchaseReturnPage(pageParams).then(res => {
        const data = unwrap(res);
        purchaseReturnList.value = data?.records || [];
        pagination.value.total = data?.total || 0;
    }).catch(error => {
        ElMessage.error('获取采购退货单列表失败');
        console.error('获取采购退货单列表失败:', error);
    });
}

// 获取采购入库单列表（用于选择）
function fetchPurchaseInbounds(excludeReturned = false) {
    const pageParams = {
        pageNum: 1,
        pageSize: 1000, // 获取足够多的入库单
        excludeReturned
    };

    getPurchaseInboundPage(pageParams).then(res => {
        const data = unwrap(res);
        purchaseInbounds.value = data?.records || [];
    }).catch(error => {
        ElMessage.error('获取采购入库单列表失败');
        console.error('获取采购入库单列表失败:', error);
    });
}

// 获取仓库列表（用于选择）
function fetchWarehouses() {
  getWarehouse().then(res => {
    const data = unwrap(res);
    warehouses.value = Array.isArray(data) ? data : [];
    console.log('仓库数据:', data);
  }).catch(error => {
    ElMessage.error('获取仓库列表失败');
    console.error('获取仓库列表失败:', error);
    console.error('错误详情:', error.response);
  });
}

// 重置搜索参数
function resetSearchParams() {
    searchParams.value = {
        returnNo: '',
        inboundNo: '',
        startDate: '',
        endDate: ''
    };
    getPurchaseReturnList();
}

// 分页处理
const handleSizeChange = (val) => {
    pagination.value.pageSize = val;
    getPurchaseReturnList();
}
const handleCurrentChange = (val) => {
    pagination.value.pageNum = val;
    getPurchaseReturnList();
}

// 处理入库单选择变化
function handleInboundChange(inboundId) {
    if (inboundId) {
        // 从入库单列表中找到选中的入库单
        const selectedInbound = purchaseInbounds.value.find(inbound => inbound.id === inboundId);
        if (selectedInbound) {
            // 自动填充仓库信息
            purchaseReturn.value.warehouseId = selectedInbound.warehouseId;
            purchaseReturn.value.warehouseName = selectedInbound.warehouseName;

            // 如果不是编辑模式，获取入库单的商品明细
            if (!isEdit.value) {
                getPurchaseInboundWithDetails(inboundId).then(res => {
                    const data = unwrap(res);
                    if (data && data.items && Array.isArray(data.items)) {
                        // 将入库单的商品明细复制到退货单
                        purchaseReturn.value.items = data.items.map(item => ({
                            productId: item.productId,
                            productName: item.productName,
                            productCode: item.productCode,
                            quantity: item.quantity,
                            unitPrice: item.unitPrice,
                            amount: item.amount
                        }));
                    } else {
                        purchaseReturn.value.items = [];
                    }
                }).catch(error => {
                    ElMessage.error('获取入库单商品明细失败');
                    console.error('获取入库单商品明细失败:', error);
                    purchaseReturn.value.items = [];
                });
            }
        }
    } else {
        // 清空仓库信息和商品明细
        purchaseReturn.value.warehouseId = null;
        purchaseReturn.value.warehouseName = '';
        purchaseReturn.value.items = [];
    }
}

// 明细操作方法
// function addItem() {
//     if (!purchaseReturn.value.items) purchaseReturn.value.items = [];
//     purchaseReturn.value.items.push({ productId: '', quantity: 1, unitPrice: 0, amount: 0 });
// }
// function removeItem(index) {
//     purchaseReturn.value.items.splice(index, 1);
// }
// function handleProductChange(row, val) {
//     // 自动带出产品名/编码等
//     const prod = productList.value.find(p => p.id === val);
//     if (prod) {
//         row.productName = prod.name;
//         row.productCode = prod.barcode || prod.code;
//         // 如果产品有默认价格，可以自动填入
//         if (prod.price && !row.unitPrice) {
//             row.unitPrice = prod.price;
//             calcAmount(row);
//         }
//     }
// }
// function calcAmount(row) {
//     row.amount = (Number(row.quantity) || 0) * (Number(row.unitPrice) || 0);
// }

// 显示创建对话框
function showAddDialog() {
    isEdit.value = false;
    purchaseReturn.value = {};
    // 初始化明细数组
    purchaseReturn.value.items = [];
    dialogVisible.value = true;
    // 仅在创建时排除已退货的入库单
    fetchPurchaseInbounds(true);

    // 延迟重置表单，确保表单引用已准备好
    setTimeout(() => {
        if (proxy.$refs.returnForm) {
            proxy.$refs.returnForm.resetFields();
        }
    }, 100);
}

// 显示编辑对话框
function showEditDialog(row) {
    isEdit.value = true;
    purchaseReturn.value = { ...row };
    // 确保明细数组存在
    if (!purchaseReturn.value.items) {
        purchaseReturn.value.items = [];
    }
    dialogVisible.value = true;
    // 编辑时需要包含该入库单选项
    fetchPurchaseInbounds(false);

    // 确保仓库名称正确显示（如果没有仓库名称，尝试从入库单获取）
    if (row.inboundId && !row.warehouseName) {
        // 延迟执行，等待入库单列表加载完成
        setTimeout(() => {
            const selectedInbound = purchaseInbounds.value.find(inbound => inbound.id === row.inboundId);
            if (selectedInbound) {
                purchaseReturn.value.warehouseName = selectedInbound.warehouseName;
                purchaseReturn.value.warehouseId = selectedInbound.warehouseId;
            }
        }, 100);
    }

    // 为每个明细项确保有正确的产品信息
    if (purchaseReturn.value.items && Array.isArray(purchaseReturn.value.items)) {
        purchaseReturn.value.items.forEach(item => {
            // 不再需要从产品列表中获取产品信息，因为商品明细现在是只读的
            // if (item.productId && !item.productName) {
            //     const product = productList.value.find(p => p.id === item.productId);
            //     if (product) {
            //         item.productName = product.name;
            //         item.productCode = product.barcode || product.code;
            //     }
            // }
            // 确保金额计算正确
            if (item.quantity && item.unitPrice) {
                item.amount = (Number(item.quantity) || 0) * (Number(item.unitPrice) || 0);
            }
        });
    }
}

// 关闭对话框
function handleDialogClose() {
    dialogVisible.value = false;
    // 重置表单（安全调用）
    if (proxy.$refs.returnForm) {
        proxy.$refs.returnForm.resetFields();
    }
    // 重置明细
    purchaseReturn.value.items = [];
}

// 提交表单
function submitForm() {
    if (!proxy.$refs.returnForm) {
        ElMessage.error('表单引用未准备好，请重试');
        return;
    }

    proxy.$refs.returnForm.validate((valid) => {
        if (valid) {
            // 明细校验 - 只在编辑模式下验证
            if (isEdit.value) {
                if (!purchaseReturn.value.items || purchaseReturn.value.items.length === 0) {
                    ElMessage.warning('请添加至少一条商品明细');
                    return;
                }
                for (const item of purchaseReturn.value.items) {
                    if (!item.productId || !item.quantity || !item.unitPrice) {
                        ElMessage.warning('请完善所有商品明细');
                        return;
                    }
                }
            } else {
                // 创建模式下，确保有商品明细（从入库单获取）
                if (!purchaseReturn.value.items || purchaseReturn.value.items.length === 0) {
                    ElMessage.warning('请先选择入库单以获取商品明细');
                    return;
                }
            }
            if (isEdit.value) {
                // 更新采购退货单
                updatePurchaseReturn(purchaseReturn.value).then(res => {
                    ElMessage.success('采购退货单更新成功');
                    handleDialogClose();
                    getPurchaseReturnList();
                }).catch(error => {
                    ElMessage.error('采购退货单更新失败');
                    console.error('更新失败:', error);
                });
            } else {
                // 创建采购退货单 - 设置必要字段
                const createData = {
                    ...purchaseReturn.value,
                    createUser: Number(localStorage.getItem("userId")) || 1,
                    tenantId: Number(localStorage.getItem("tenantId")) || 1
                };

                createPurchaseReturn(createData).then(res => {
                    ElMessage.success('采购退货单创建成功');
                    handleDialogClose();
                    getPurchaseReturnList();
                }).catch(error => {
                    ElMessage.error('采购退货单创建失败');
                    console.error('创建失败:', error);
                });
            }
        } else {
            ElMessage.warning('请完善采购退货单信息并确保格式正确');
            return false;
        }
    });
}

// 查看采购退货单详情
function viewPurchaseReturnDetails(id) {
    // 调用获取采购退货单详情的API
    getPurchaseReturnWithDetails(id).then(res => {
        const data = unwrap(res);
        currentPurchaseReturn.value = data || null;
        detailDialogVisible.value = true;
    }).catch(error => {
        ElMessage.error('获取采购退货单详情失败');
        console.error('获取详情失败:', error);
    });
}

// 关闭详情对话框
function handleDetailDialogClose() {
    detailDialogVisible.value = false;
    currentPurchaseReturn.value = null;
}

// 删除采购退货单
function handleDeletePurchaseReturn(id) {
    ElMessageBox.confirm(
        '确定要删除该采购退货单吗？此操作不可撤销。',
        '删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        // 调用删除采购退货单的API
        deletePurchaseReturn(id).then(res => {
            ElMessage.success('采购退货单删除成功');
            getPurchaseReturnList();
        }).catch(error => {
            ElMessage.error('采购退货单删除失败');
            console.error('删除失败:', error);
        });
    }).catch(() => {
        ElMessage.info('已取消删除');
    });
}

// 页面加载时获取采购退货单列表、采购入库单列表和仓库列表
onMounted(() => {
    getPurchaseReturnList();
    // 初始加载包含全部入库单（便于编辑场景）
    fetchPurchaseInbounds(false);
    fetchWarehouses();
    // 不再需要获取产品列表，因为商品明细现在是只读的
    // getProductList().then(res => {
    //     const data = unwrap(res);
    //     productList.value = Array.isArray(data) ? data : [];
    // });
});
</script>

<style scoped>
.purchase-return-container {
    padding: 20px;
}

.search-bar {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}

.purchase-detail {
    padding: 10px;
}

.detail-header {
    margin-bottom: 20px;
}

.detail-header p {
    margin: 8px 0;
}

.label {
    font-weight: bold;
    display: inline-block;
    width: 100px;
}

.detail-items h3 {
    margin-bottom: 10px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}
</style>
